# -*- coding: utf-8 -*-
# @Time    : 2019/10/24 16:12
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : thread_condition.py
import threading
# 通过condition完成按序执行
from threading import Condition
lock = threading.Lock()



class XiaoAi(threading.Thread):
    def __init__(self, cond):
        self.cond = cond
        super(XiaoAi, self).__init__(name="小爱")

    def run(self) -> None:
        with self.cond:
            self.cond.wait()
            print(f"{self.name}: 在")
            self.cond.notify()
            self.cond.wait()
            print(f"{self.name}: 没吃")
            self.cond.notify()
            self.cond.wait()
            print(f"{self.name}: 好")
            self.cond.notify()


class TianMao(threading.Thread):
    def __init__(self, cond):
        self.cond = cond
        super(TianMao, self).__init__(name="天猫精灵")

    def run(self) -> None:
        with self.cond.acquire():
            print(f"{self.name}: 小爱同学")
            self.cond.notify()
            self.cond.wait()
            print(f"{self.name}: 吃了吗")
            self.cond.notify()
            self.cond.wait()
            print(f"{self.name}: 吃火锅好吗")
            self.cond.notify()

            self.cond.release()


if __name__ == '__main__':

    cond = threading.Condition()
    xiaoai = XiaoAi(cond)
    tianmao = TianMao(cond)

    # condition的启动顺序很重要
    # tianmao先start时
    """
     print(f"{self.name}: 小爱同学")
     self.cond.notify()
     小爱还没有start起来
     wait只有notify才能唤醒
     而此时天猫已经发过notify了
     所以调用小爱线程后会一直等待无法被唤醒
    """
    # 在调用with self.cond: 后才能调用wait或notify方法
    # condition有两层锁，一把底层锁，会在线程调用了wait方法的时候释放，
    # 上面的锁会在每次调用wait的时候分配一把并放入到cond的等待队列中，等到notify方法的唤醒
    xiaoai.start()
    tianmao.start()